#include "stdafx.h"
#include "MainFrame.h"
#include "Renderer.h"
#include "Scene.h"

CMainFrame::CMainFrame()
: m_pRenderer(NULL)
, m_pScene(NULL)
{
}

CMainFrame::~CMainFrame()
{
	delete m_pRenderer;
	delete m_pScene;
}

SDL_Surface& CMainFrame::InitSDL()
{
	atexit(SDL_Quit);

	if(SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		cerr << "Unable to initialise SDL: " << SDL_GetError();
		exit(0);
	}

	SDL_Surface* screen = SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 0, SDL_OPENGL);

	if(screen == 0)
	{
		cerr << "Unable to set OpenGL videomode: " << SDL_GetError();
		SDL_Quit();
		exit(0);
	}

	SDL_EnableUNICODE(1) ;
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
	SDL_WM_SetCaption("Rasterizer_chpark", "Rasterizer_chpark");

	return *screen;
}

void CMainFrame::HandleInput(bool &bQuit)
{
	SDL_Event e;

	while(SDL_PollEvent(&e))
	{
		switch(e.type)
		{
		case SDL_MOUSEMOTION:
		case SDL_MOUSEBUTTONDOWN:
		case SDL_MOUSEBUTTONUP:
		case SDL_KEYDOWN:
		case SDL_KEYUP:
			break;

		case SDL_QUIT:
			bQuit = true;
			break;

		case SDL_VIDEORESIZE:
			break;
		}
	}
}

bool CMainFrame::Init(const char* pFileName)
{
	SDL_Surface& screen = InitSDL();

	m_pRenderer = new CRenderer;
	m_pRenderer->Init();

	m_pScene = new CScene;
	return m_pScene->Init(pFileName);
}

void CMainFrame::Render()
{
	glClear(GL_COLOR_BUFFER_BIT);

	m_pRenderer->Render(m_pScene);
	m_pRenderer->UpdateFrame();

	SDL_GL_SwapBuffers();
}

void CMainFrame::MainLoop()
{
	bool bQquit = false ;

	double dLastTimePulse = 0.001 * static_cast<double>(SDL_GetTicks());

	while(!bQquit)
	{
		HandleInput(bQquit);

		Render();
	}
}
